package com.example.mykotlinapp

import java.io.File

/**
 *
 * 复习 object关键字使用
 *
 * @author zhudeshuai
 * @since 2019/7/17
 */


//object关键字实现单例

//下载单例
object DownLoadManager {
    fun startDownload() {
        println("start download...")
    }

    fun pauseDownload() {
        println("pause download...")
    }

}

//单例可以继承或者实现接口
object CaseInsensitiveFileComparator : Comparator<File> {
    override fun compare(o1: File, o2: File): Int {
        return o1.path.compareTo(o2.path, true)
    }

}

private fun test120() {
    DownLoadManager.startDownload()
    println(CaseInsensitiveFileComparator.compare(File("/User"), File("/user")))
    val list = listOf(File("/Z"), File("/b"))
    println(list.sortedWith(CaseInsensitiveFileComparator))

}

//关键字companion 伴生对象---->类似java类中静态方法
private class B {
    companion object {
        fun bar() {
            println("companion object is called")
        }
    }
}

//伴生对象可以访问类中的private的构造方法，属性等。所以适合实现工厂方法

interface IBaseView {
    fun layout()
    fun measure()
    fun draw()
}

class AView : IBaseView {
    override fun measure() {
    }

    override fun draw() {
    }

    override fun layout() {

    }
}

class BView : IBaseView {
    override fun layout() {
    }

    override fun measure() {
    }

    override fun draw() {
    }
}

class CView : IBaseView {
    override fun layout() {
    }

    override fun measure() {
    }

    override fun draw() {
    }

}

//实例工厂
private class Factory {
    companion object {
        fun createFactory(type: Int): IBaseView =
            when (type) {
                1 -> AView()
                2 -> BView()
                3 -> CView()
                else -> CView()
            }
    }
}

//伴生对象可以有名字，可以实现接口

private interface ILoader {
    fun load()
}

private class C {
    companion object : ILoader {
        override fun load() {
            println("loading...")
        }

        fun reload() {

        }
    }
}

private fun loadResource(loader: ILoader) {

}

private fun test121() {
    B.bar()
    println(Factory.createFactory(2))
    C.reload()
    Factory.Companion.createFactory(2)//没有定义名字默认为Companion

    loadResource(C)//C被当做自身的伴生对象使用
}


//object关键字 对象表达式 Java中的匿名内部类


private fun test122() {

}

private fun main() {


}